﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.IO;
using System.Linq;
using Lucene.Linq.Search;
using Lucene.Linq.Utility;

namespace Lucene.Linq.Storage.EntityFramework
{
    class DatabaseIndexSetIncremental<T> : DatabaseIndexSet<T>
        where T : DataContext
    {
        public DatabaseIndexSetIncremental(T dataContext)
            : base(dataContext)
        { }

        public DatabaseIndexSetIncremental(string path, T dataContext)
            : base(path, dataContext)
        { }

        public DatabaseIndexSetIncremental(DirectoryInfo directory, T dataContext)
            : base(directory, dataContext)
        { }

        /// <summary>Write all the records from the table type into their respective indexes</summary>
        /// <typeparam name="TTable">Table type to index</typeparam>
        /// <typeparam name="TKey"></typeparam>
        public void Write<TTable, TKey>(IEnumerable<TTable> query)
            where TTable : class, IUniqueKey<TKey>
        {
            Write<TTable, TKey>(typeof(TTable), query);
        }

        /// <summary>Write all the records from the table type into their respective indexes</summary>
        /// <param name="tableType">Table type to index</param>
        /// <param name="query"> </param>
        public void Write<TTable, TKey>(Type tableType, IEnumerable<TTable> query)
            where TTable : class, IUniqueKey<TKey>
        {
            if (query == null || (query.Count() == 0))
            {
                return;
            }

            using (_dataContextLock.ReadLock())
            {
                IIndex<TTable> index = Get<TTable>();
                string name = tableType.Name;

                // Get the LINQ to SQL ITable instance
                ITable table = DataContext.GetTable(tableType);
                if (table == null)
                    throw new ArgumentException("tableType doesnt belong to db");

                // get all records from the query
                IEnumerable<TTable> items = query.ToList();

                System.Diagnostics.Debug.Write("About to write " + name + "s...");

                int i = 0;
                foreach (TTable item in items)
                {
                    TTable indexItem = DataContext.Get<TTable, TKey>(item.Key);
                    if (indexItem != null)
                    {
                        // update index element
                        index.Delete(indexItem.Key);
                    }
                    // add new/updated index element
                    index.Add(item);
                    i++;
                    System.Diagnostics.Debug.WriteLine("Added Index " + i.ToString() + ", Key '" + item.Key + "', Name '" + name + "'.");
                }
            }
        }
    }
}
